#!/bin/bash

# XAppTool API 测试脚本
# 包含所有API接口的测试

set -e

# 配置
API_BASE_URL="http://php-test:9000/api"
RESULTS_DIR="/var/www/test-results"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
TEST_REPORT="$RESULTS_DIR/api_test_report_$TIMESTAMP.json"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0
SKIPPED_TESTS=0

# 初始化测试报告
init_report() {
    echo "{" > "$TEST_REPORT"
    echo "  \"timestamp\": \"$TIMESTAMP\"," >> "$TEST_REPORT"
    echo "  \"api_base_url\": \"$API_BASE_URL\"," >> "$TEST_REPORT"
    echo "  \"tests\": [" >> "$TEST_REPORT"
}

# 添加测试结果到报告
add_test_result() {
    local test_name="$1"
    local status="$2"
    local response_code="$3"
    local response_body="$4"
    local error_message="$5"
    
    if [ $TOTAL_TESTS -gt 0 ]; then
        echo "," >> "$TEST_REPORT"
    fi
    
    echo "    {" >> "$TEST_REPORT"
    echo "      \"name\": \"$test_name\"," >> "$TEST_REPORT"
    echo "      \"status\": \"$status\"," >> "$TEST_REPORT"
    echo "      \"response_code\": $response_code," >> "$TEST_REPORT"
    echo "      \"response_body\": $(echo "$response_body" | jq -R .)," >> "$TEST_REPORT"
    echo "      \"error_message\": $(echo "$error_message" | jq -R .)," >> "$TEST_REPORT"
    echo "      \"timestamp\": \"$(date '+%Y-%m-%d %H:%M:%S')\"" >> "$TEST_REPORT"
    echo "    }" >> "$TEST_REPORT"
}

# 完成测试报告
finalize_report() {
    echo "  ]," >> "$TEST_REPORT"
    echo "  \"summary\": {" >> "$TEST_REPORT"
    echo "    \"total\": $TOTAL_TESTS," >> "$TEST_REPORT"
    echo "    \"passed\": $PASSED_TESTS," >> "$TEST_REPORT"
    echo "    \"failed\": $FAILED_TESTS," >> "$TEST_REPORT"
    echo "    \"skipped\": $SKIPPED_TESTS," >> "$TEST_REPORT"
    echo "    \"success_rate\": $(echo "scale=2; $PASSED_TESTS * 100 / $TOTAL_TESTS" | bc -l)" >> "$TEST_REPORT"
    echo "  }" >> "$TEST_REPORT"
    echo "}" >> "$TEST_REPORT"
}

# 测试函数
test_api() {
    local test_name="$1"
    local method="$2"
    local endpoint="$3"
    local data="$4"
    local expected_status="$5"
    
    echo -n "Testing: $test_name ... "
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    local response_file=$(mktemp)
    local status_code
    
    if [ "$method" = "GET" ]; then
        status_code=$(curl -s -o "$response_file" -w "%{http_code}" "$API_BASE_URL$endpoint")
    else
        status_code=$(curl -s -o "$response_file" -w "%{http_code}" -X "$method" -H "Content-Type: application/json" -d "$data" "$API_BASE_URL$endpoint")
    fi
    
    local response_body=$(cat "$response_file")
    rm -f "$response_file"
    
    if [ "$status_code" = "$expected_status" ]; then
        echo -e "${GREEN}PASSED${NC} (HTTP $status_code)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        add_test_result "$test_name" "passed" "$status_code" "$response_body" ""
    else
        echo -e "${RED}FAILED${NC} (Expected $expected_status, got $status_code)"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        add_test_result "$test_name" "failed" "$status_code" "$response_body" "Expected HTTP $expected_status but got $status_code"
    fi
}

# 健康检查测试
test_health_check() {
    echo -e "\n${YELLOW}=== 健康检查测试 ===${NC}"
    test_api "Health Check" "GET" "/health" "" "200"
}

# 性能监控测试
test_performance_monitoring() {
    echo -e "\n${YELLOW}=== 性能监控测试 ===${NC}"
    test_api "Performance Metrics" "GET" "/performance/metrics" "" "200"
    test_api "System Status" "GET" "/performance/status" "" "200"
}

# 认证测试
test_authentication() {
    echo -e "\n${YELLOW}=== 认证测试 ===${NC}"
    
    # 用户注册
    local register_data='{"username":"testuser","email":"test@example.com","password":"testpass123","password_confirmation":"testpass123"}'
    test_api "User Registration" "POST" "/auth/register" "$register_data" "200"
    
    # 用户登录
    local login_data='{"email":"test@example.com","password":"testpass123"}'
    test_api "User Login" "POST" "/auth/login" "$login_data" "200"
    
    # 商户注册
    local merchant_register_data='{"merchant_name":"Test Merchant","email":"merchant@example.com","password":"merchant123","password_confirmation":"merchant123"}'
    test_api "Merchant Registration" "POST" "/auth/merchant/register" "$merchant_register_data" "200"
    
    # 商户登录
    local merchant_login_data='{"email":"merchant@example.com","password":"merchant123"}'
    test_api "Merchant Login" "POST" "/auth/merchant/login" "$merchant_login_data" "200"
}

# 应用管理测试
test_app_management() {
    echo -e "\n${YELLOW}=== 应用管理测试 ===${NC}"
    
    # 创建应用 (需要先登录获取token)
    local create_app_data='{"app_name":"Test App","app_description":"Test application","platform":"web"}'
    test_api "Create App" "POST" "/apps" "$create_app_data" "401" # 需要认证
    
    # 获取应用列表
    test_api "Get App List" "GET" "/apps" "" "401" # 需要认证
    
    # 获取应用详情
    test_api "Get App Details" "GET" "/apps/1" "" "401" # 需要认证
}

# 会员系统测试
test_membership() {
    echo -e "\n${YELLOW}=== 会员系统测试 ===${NC}"
    
    # 获取会员等级
    test_api "Get Membership Tiers" "GET" "/membership/tiers" "" "200"
    
    # 获取会员权益
    test_api "Get Membership Benefits" "GET" "/membership/benefits" "" "200"
}

# SDK管理测试
test_sdk_management() {
    echo -e "\n${YELLOW}=== SDK管理测试 ===${NC}"
    
    # 获取SDK配置
    test_api "Get SDK Config" "GET" "/sdk/config" "" "200"
    
    # 获取SDK版本
    test_api "Get SDK Versions" "GET" "/sdk/versions" "" "200"
}

# 数据统计测试
test_analytics() {
    echo -e "\n${YELLOW}=== 数据统计测试 ===${NC}"
    
    # 获取应用统计
    test_api "Get App Statistics" "GET" "/analytics/apps/stats" "" "401" # 需要认证
    
    # 获取用户统计
    test_api "Get User Statistics" "GET" "/analytics/users/stats" "" "401" # 需要认证
}

# 安全测试
test_security() {
    echo -e "\n${YELLOW}=== 安全测试 ===${NC}"
    
    # 测试速率限制
    echo -n "Testing: Rate Limiting ... "
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    local rate_limit_passed=true
    for i in {1..15}; do
        local response=$(curl -s -w "\n%{http_code}" "$API_BASE_URL/health")
        local status_code=$(echo "$response" | tail -n1)
        
        if [ $i -gt 10 ] && [ "$status_code" != "429" ]; then
            rate_limit_passed=false
            break
        fi
    done
    
    if [ "$rate_limit_passed" = true ]; then
        echo -e "${GREEN}PASSED${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        add_test_result "Rate Limiting" "passed" "429" "" ""
    else
        echo -e "${RED}FAILED${NC}"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        add_test_result "Rate Limiting" "failed" "200" "" "Rate limiting not working properly"
    fi
    
    # 测试SQL注入防护
    local sql_injection_data='{"email":"test@example.com\' OR 1=1--","password":"test"}'
    test_api "SQL Injection Protection" "POST" "/auth/login" "$sql_injection_data" "400"
}

# 运行所有测试
run_all_tests() {
    echo -e "${YELLOW}开始XAppTool API测试...${NC}"
    echo "API基础地址: $API_BASE_URL"
    echo "测试报告将保存到: $TEST_REPORT"
    echo ""
    
    init_report
    
    # 等待服务启动
    echo "等待服务启动..."
    sleep 10
    
    # 运行测试套件
    test_health_check
    test_performance_monitoring
    test_authentication
    test_app_management
    test_membership
    test_sdk_management
    test_analytics
    test_security
    
    finalize_report
    
    # 输出测试总结
    echo -e "\n${YELLOW}=== 测试总结 ===${NC}"
    echo "总测试数: $TOTAL_TESTS"
    echo -e "通过: ${GREEN}$PASSED_TESTS${NC}"
    echo -e "失败: ${RED}$FAILED_TESTS${NC}"
    echo -e "跳过: ${YELLOW}$SKIPPED_TESTS${NC}"
    echo "成功率: $(echo "scale=2; $PASSED_TESTS * 100 / $TOTAL_TESTS" | bc -l)%"
    
    # 生成HTML报告
    generate_html_report
    
    # 返回测试结果
    if [ $FAILED_TESTS -eq 0 ]; then
        echo -e "\n${GREEN}所有测试通过!${NC}"
        exit 0
    else
        echo -e "\n${RED}测试失败，请查看详细报告。${NC}"
        exit 1
    fi
}

# 生成HTML报告
generate_html_report() {
    local html_report="${TEST_REPORT%.json}.html"
    
    cat > "$html_report" << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XAppTool API 测试报告</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .header { background-color: #f4f4f4; padding: 20px; border-radius: 5px; }
        .summary { margin: 20px 0; }
        .test-result { margin: 10px 0; padding: 10px; border-radius: 5px; }
        .passed { background-color: #d4edda; border: 1px solid #c3e6cb; }
        .failed { background-color: #f8d7da; border: 1px solid #f5c6cb; }
        .skipped { background-color: #fff3cd; border: 1px solid #ffeaa7; }
        .details { margin-top: 10px; font-size: 0.9em; }
        .code { background-color: #f8f9fa; padding: 10px; border-radius: 3px; font-family: monospace; }
    </style>
</head>
<body>
    <div class="header">
        <h1>XAppTool API 测试报告</h1>
        <p>测试时间: <span id="timestamp"></span></p>
        <p>API地址: <span id="api-url"></span></p>
    </div>
    
    <div class="summary" id="summary">
        <h2>测试总结</h2>
        <div id="summary-content"></div>
    </div>
    
    <div id="test-results">
        <h2>详细测试结果</h2>
    </div>
    
    <script>
        // 这里将通过JavaScript动态加载JSON数据并生成报告
        fetch('$(basename "$TEST_REPORT")')
            .then(response => response.json())
            .then(data => {
                document.getElementById('timestamp').textContent = data.timestamp;
                document.getElementById('api-url').textContent = data.api_base_url;
                
                const summary = data.summary;
                document.getElementById('summary-content').innerHTML = `
                    <p>总测试数: ${summary.total}</p>
                    <p>通过: <span style="color: green">${summary.passed}</span></p>
                    <p>失败: <span style="color: red">${summary.failed}</span></p>
                    <p>跳过: <span style="color: orange">${summary.skipped}</span></p>
                    <p>成功率: <strong>${summary.success_rate}%</strong></p>
                `;
                
                const resultsDiv = document.getElementById('test-results');
                data.tests.forEach(test => {
                    const testDiv = document.createElement('div');
                    testDiv.className = `test-result ${test.status}`;
                    testDiv.innerHTML = `
                        <h3>${test.name}</h3>
                        <p>状态: <strong>${test.status.toUpperCase()}</strong></p>
                        <p>响应码: ${test.response_code}</p>
                        ${test.error_message ? `<p>错误: ${test.error_message}</p>` : ''}
                        ${test.response_body ? `<div class="details">
                            <p>响应内容:</p>
                            <div class="code">${test.response_body}</div>
                        </div>` : ''}
                    `;
                    resultsDiv.appendChild(testDiv);
                });
            })
            .catch(error => {
                console.error('加载测试数据失败:', error);
                document.getElementById('test-results').innerHTML = '<p style="color: red">加载测试数据失败</p>';
            });
    </script>
</body>
</html>
EOF
}

# 主函数
main() {
    echo "XAppTool API 测试启动器"
    echo "========================"
    
    # 创建结果目录
    mkdir -p "$RESULTS_DIR"
    
    # 运行测试
    run_all_tests
}

# 如果直接运行此脚本
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
    main "$@"
fi